package com.xoms.admin.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.xoms.admin.controller.res.bean.RProBreakageBean;
import com.xoms.admin.controller.res.bean.RProBreakageInfoBean;
import com.xoms.admin.model.AccountBean;
import com.xoms.admin.model.AuditBean;
import com.xoms.admin.model.ProBreakageBean;
import com.xoms.admin.model.ProBreakageDetailBean;
import com.xoms.admin.model.vo.BatchBreakageBean;
import com.xoms.admin.persist.dao.ProAuditDao;
import com.xoms.admin.persist.dao.ProBreakageDao;
import com.xoms.admin.service.ProBreakageService;
import com.xoms.admin.service.exception.ServiceException;
import com.xoms.admin.service.res.PageResult;
import com.xoms.util.AppTextUtil;
import com.xoms.util.DateTimeUtil;
import com.xoms.util.NumUtil;
import com.xoms.util.StringUtil;

@Service
public class ProBreakageServiceImpl implements  ProBreakageService {
	
	Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	ProBreakageDao proBreakageImpl;

	@Autowired
	ProAuditDao proAuditImpl;

	@Override
	public PageResult<RProBreakageBean> getBreakages(AccountBean account, int page, int pageSize, String startTime,
			String endTime, String storeId) {
		PageResult<RProBreakageBean> result = new PageResult<RProBreakageBean>();
		List<RProBreakageBean> resList = new ArrayList<RProBreakageBean>();
		// 获取报损数量
		int count = proBreakageImpl.selectCount(startTime, endTime, storeId);
		if(count > 0) {
			//查询报损列表
			List<ProBreakageBean> lists = proBreakageImpl.selectList(page, pageSize, startTime, endTime, storeId);

			if (lists != null) {
				RProBreakageBean rb = null;
				for (ProBreakageBean pb : lists) {
					rb=parse(pb);
					resList.add(rb);
				}
			}
		}
		
		result.setData(resList);
		result.setCount(count);
		return result;
	}
	
	/**
	 * 格式化数据
	 * @param acc
	 * @return
	 */
	private RProBreakageBean parse(ProBreakageBean pro) {
		RProBreakageBean res = new RProBreakageBean();
		res.setAccount(pro.getAccount());
		res.setAccountId(pro.getAccount());
		res.setBid(pro.getBid());
		res.setBreakageNo(pro.getBreakageNo());
		res.setRemark(pro.getRemark());
		res.setReview(pro.getReview());
		res.setStatus(pro.getStatus());
		res.setStoreHouse(pro.getStoreHouse());
		res.setStoreHouseId(pro.getStoreHouseId());
		res.setCreateTime(DateTimeUtil.formatTimestamp(pro.getCreateTime()));
		return res;
	}
	
	@Override
	public PageResult<RProBreakageInfoBean> getBreakageDetails(AccountBean account, int page, int pageSize, String bid,
			int paging) {
		PageResult<RProBreakageInfoBean> result = new PageResult<RProBreakageInfoBean>();
		List<RProBreakageInfoBean> resList = new ArrayList<RProBreakageInfoBean>();
		int count = proBreakageImpl.selectDetailCount(bid);
		if(count > 0) {
			//查询采购单列表
			List<ProBreakageDetailBean> lists = proBreakageImpl.selectDetailList(bid, page, pageSize, paging);
			if (lists != null) {
				RProBreakageInfoBean rb = null;
				for (ProBreakageDetailBean br : lists) {
					rb = new RProBreakageInfoBean();
					rb = parseDetail(br);
					resList.add(rb);
				}
			}
		}
		result.setData(resList);
		result.setCount(count);
		return result;
	}
	
	/**
	 * 格式化详情
	 * @param pur
	 * @return
	 */
	private RProBreakageInfoBean parseDetail(ProBreakageDetailBean br) {
		RProBreakageInfoBean res = new RProBreakageInfoBean();
		res.setBreakageId(br.getBreakageId());
		res.setBreakageNo(br.getBreakageNo());
		res.setCategory(br.getCategory());
		res.setNumber(br.getNumber());
		res.setPrice(br.getPrice());
		res.setProduct(br.getProduct());
		res.setProductBar(br.getProductBar());
		res.setProductId(br.getProductId());
		res.setUnit(br.getUnit());
		return res;
	}

	@Transactional(rollbackFor = Exception.class)// 事务
	@Override
	public RProBreakageBean edit(AccountBean account, String bid, String storeId, String remark, String details,
			int isSubmit) {
		boolean flag = false;
		ProBreakageBean data = new ProBreakageBean();
		data.setStoreHouseId(storeId);
		data.setRemark(remark);

		if (StringUtil.isEmpty(bid)) {// 新建
			bid = AppTextUtil.getPrimaryKey();// id
			data.setBid(bid);
			data.setAccountId(account.getAccid());
			
			data.setStatus(isSubmit);// 未提交审核

			// 采购编号：BS + YYYYMMDDHHmm + 0000001;一年百万数据？
			String maxNo = proBreakageImpl.selectMaxNoInYear();// 获取当年报损单最大数量
			int num = 0;
			if(!StringUtil.isEmpty(maxNo)) {
				num = NumUtil.toInt(maxNo.substring(maxNo.length() - 7, maxNo.length()), 0);
			}
			String breakNo = AppTextUtil.getRandomProNo("BS", (num + 1), 7);
			data.setBreakageNo(breakNo);

			flag = proBreakageImpl.insert(data) > 0;
			if (!flag) {
				throw new ServiceException("database_insert_fail","报损订单");
			}
			if(isSubmit == 2) { // 直接提交审核

				flag = submitAudit(account, bid, 4);
			}
			
		} else {
			data.setBid(bid);
			flag = proBreakageImpl.update(data) > 0;// 更新数据库
			if (!flag) {
				throw new ServiceException("database_update_fail","采购订单");
			}
		}
		// 将采购商品详情信息批量更新到数据库
		if(!StringUtil.isEmpty(details)) { 
			flag = replaceBatchDetail(bid, details);
		}
		ProBreakageBean res = proBreakageImpl.selectOneById(bid);
		return parse(res);
	}
	
	/**
	 * 批量更新数据
	 * @param bid
	 * @param details
	 * @return
	 */
	private boolean replaceBatchDetail(String bid, String details) {
		boolean flag = false;
		// JSON转list
		List<BatchBreakageBean> batch = JSON.parseArray(details, BatchBreakageBean.class);
		for(BatchBreakageBean breakage : batch) {
			breakage.setBreakageId(bid);
		}
		if(batch.size() > 0) {
			// 删除历史记录，
			// 判断数量
			int detailCount = proBreakageImpl.selectDetailCount(bid);
			if(detailCount > 0) {
				// 删除当前采购单下所有关联采购单详情
				flag = proBreakageImpl.delDetails(bid) > 0;
				if (!flag) {
					throw new ServiceException("database_delete_fail", "报损单详情");
				}
			}
			// 批量更新
			flag = proBreakageImpl.replaceBatchDetail(batch) > 0;
			if (!flag) {
				throw new ServiceException("database_insert_fail","报损详情");
			}
		}
		return flag;
	}

	@Transactional(rollbackFor = Exception.class)// 事务
	@Override
	public boolean del(AccountBean account, String bid) {
		boolean flag = false;
		// 删除报损前判断是否已提交，提交的报损单不能删除
		ProBreakageBean breakage = proBreakageImpl.selectOneById(bid);
		if(breakage == null) {// 采购单不存在
			throw new ServiceException("object_is_not_exist","报损单");
		}
		int status = NumUtil.toInt(breakage.getStatus(), 1);
		if(status != 1) {
			throw new ServiceException("object_is_submit", "报损单");
		}
		
		flag = proBreakageImpl.del(bid) > 0;
		if (!flag) {
			throw new ServiceException("database_delete_fail", "报损单");
		}
		// 判断数量
		int detailCount = proBreakageImpl.selectDetailCount(bid);
		if(detailCount > 0) {
			// 删除当前采购单下所有关联采购单详情
			flag = proBreakageImpl.delDetails(bid) > 0;
			if (!flag) {
				throw new ServiceException("database_delete_fail", "报损单详情");
			}
		}
		return flag;
	}

	@Transactional(rollbackFor = Exception.class)// 事务
	@Override
	public boolean submitPurchase(AccountBean account, String bid) {
		boolean flag = false;
		// 提交采购单前判断是否是待提交状态，提交的采购单不能多次提交
		ProBreakageBean breakage = proBreakageImpl.selectOneById(bid);
		if(breakage == null) {// 采购单不存在
			throw new ServiceException("object_is_not_exist","报损单");
		}
		int status = breakage.getStatus();
		if(status != 1 && status != 4) {
			throw new ServiceException("object_is_not_unsubmit", "报损单");
		}
		flag = proBreakageImpl.updateSubmitStatus(bid, 2) > 0;// 更新采购单状态,1提交待审核
		if (!flag) {// 更新状态失败
			throw new ServiceException("database_update_fail","报损审核状态");
		}
		flag = submitAudit(account, bid, 4);
		return flag;
	}

	private boolean submitAudit(AccountBean account, String targetId, int type) {
		boolean flag;
		AuditBean audit = new AuditBean();// 添加到审核表
		audit.setAid(AppTextUtil.getPrimaryKey());
		audit.setSubmitId(account.getAccid());
		audit.setType(type);// 审核类型：1采购2入库3盘库4损耗5充公6冲正7退货到供应商
		audit.setTargetId(targetId);// 关联id
		// 审核编号：SH+ YYYYMMDDHHmm + 0000001;一年百万数据？
		String maxNo = proAuditImpl.selectMaxAuditNoInYear(type);// 获取当年审核单最大数量
		int num = 0;
		if(!StringUtil.isEmpty(maxNo)) {
			num = NumUtil.toInt(maxNo.substring(maxNo.length() - 7, maxNo.length()), 0);
		}
		String auditNo = AppTextUtil.getRandomProNo("SH", (num + 1), 7);
		audit.setAuditNo(auditNo);
		audit.setStatus(0);
		
		flag = proAuditImpl.insert(audit) > 0;
		if (!flag) {// 插入状态失败
			throw new ServiceException("database_insert_fail","报损审核提交");
		}
		return flag;
	}

	
}
